//
//  WPRightManagerViewModel.m
//  ZhongChouPingTai
//
//  Created by WeiPan on 16/4/13.
//  Copyright © 2016年 WPJoe. All rights reserved.
//

#import "WPRightManagerViewModel.h"
#import "WPRightManageDetailModel.h"
#import "WPTransRightManageHeadModel.h"

@implementation WPRightManagerViewModel
+ (void)getTransedTicketListWithPageNumber:(NSInteger)page andIsUsable:(BOOL)isUsable andWithOrderID:(NSNumber *)orderid andSuccessBlock:(void (^)(NSMutableArray *, NSInteger))success andFailureBlock:(void (^)(NSString *))failure {
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary: @{@"pageNumber":@(page),@"pageSize":@(10),@"memberid":[UserModel defaultUser].userID}];
    if (orderid) {
        params[@"orderid"] = orderid;
    }
    [NetWorkingManager postWithUrl:!isUsable ? @"commoditytrade/rightsVendibility.jhtml": @"commoditytrade/rightsDisabled.jhtml" requestParams:[NetWorkingManager paramsByAppendingUserInfo:params] SuccessHandler:^(id responseObject) {
        if (responseObject[@"resultType"] && [responseObject[@"resultType"] intValue]) {
            NSMutableArray * resultArr = [NSMutableArray arrayWithCapacity:0];
            if (responseObject[@"resultMsg"] &&[responseObject[@"resultMsg"] isKindOfClass:[NSArray class]]) {
                for (int i = 0; i < [responseObject[@"resultMsg"] count]; i++) {
                    NSMutableArray * sigleArr = [NSMutableArray arrayWithCapacity:0];
                    WPTransRightManageHeadModel * headModel = [WPTransRightManageHeadModel new];
                    [headModel setValuesForKeysWithDictionary:responseObject[@"resultMsg"][i]];
                    [sigleArr addObject:headModel];
                    NSMutableArray * tickets = [NSMutableArray arrayWithCapacity:0];
                    for (NSDictionary * dic in responseObject[@"resultMsg"][i][@"products"]) {
                        WPRightManageDetailModel * detailModel = [WPRightManageDetailModel new];
                        [detailModel setValuesForKeysWithDictionary:dic];
                        [tickets addObject:detailModel];
                    }
                    [sigleArr addObject:tickets];
                    [resultArr addObject:sigleArr];
                }
                success(resultArr, 1);
            } else {
                failure(responseObject[@"resultMsg"]?responseObject[@"rsultMsg"]:@"无数据");
            }
        } else {
            failure(responseObject[@"resultMsg"] && [responseObject[@"resultMsg"] length] ?responseObject[@"resultMsg"]:@"暂无数据");
        }
    } failureHandler:^(NSError *error) {
        failure(error.localizedDescription);
    }];
}
+ (void)transTicketWithGoogId:(NSNumber *)goodId andWithSaleType:(NSNumber *)saleType andWithProductIds:(NSArray *)tickedIds andSalePrice:(NSString *)salePrice andWithSuccessBlock:(void (^)(NSString *))success andWithFailureBlock:(void (^)(NSString *))failure {
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:@{@"goodsid":goodId,@"saleType":saleType,@"memberid":[UserModel defaultUser].userID}];
    if (salePrice) {
        NSDictionary * data = @{@"productIds":[self ticketIdSToJsonWithTicketId:tickedIds], @"salePrice":salePrice, @"productId":@(0)};
//        params[@"data"] = [self :tickedIds];
        params[@"data"] = [self dictionaryToJson:data];
    } else {
        params[@"data"] = [self arrayToJsonWithArray:tickedIds];
    }
    
    [NetWorkingManager postWithUrl:@"commoditytrade/transferTicket.jhtml" requestParams:[NetWorkingManager paramsByAppendingUserInfo:params] SuccessHandler:^(id responseObject) {
        if (responseObject[@"resultType"] && [responseObject[@"resultType"] intValue]) {
            success(@"转卖成功");
        } else {
            failure(responseObject[@"resultMsg"]?responseObject[@"resultMsg"]:@"转卖失败");
        }
    } failureHandler:^(NSError *error) {
        failure(error.localizedDescription);
    }];
}
+ (NSString *)ticketIdSToJsonWithTicketId:(NSArray *)arr {
    NSMutableString * jsonString = [[NSMutableString alloc]initWithString:@"["];
    for (NSNumber * num in arr) {
        NSString *string;
        
        string  = [NSString stringWithFormat:
                   @"%@,", num];
        [jsonString appendString:string];
    }
    // 3. 获取末尾逗号所在位置
    NSUInteger location = [jsonString length]-1;
    
    NSRange range       = NSMakeRange(location, 1);
    
    // 4. 将末尾逗号换成结束的]}
    [jsonString replaceCharactersInRange:range withString:@"]"];
    
    NSLog(@"jsonString = %@",jsonString);
    return jsonString;
}
+ (NSString *)arrayToJsonWithArray:(NSArray *)arr {
    //1. 初始化可变字符串，存放最终生成json字串
    NSMutableString *jsonString = [[NSMutableString alloc] initWithString:@"["];
    
    for(NSDictionary * dic in arr){
        
        //2. 遍历数组，取出键值对并按json格式存放
        NSString *string;
        
        string  = [NSString stringWithFormat:
                   @"%@,",[self dictionaryToJson:dic]];
        
        [jsonString appendString:string];
        
    }
    // 3. 获取末尾逗号所在位置
    NSUInteger location = [jsonString length]-1;
    
    NSRange range       = NSMakeRange(location, 1);
    
    // 4. 将末尾逗号换成结束的]}
    [jsonString replaceCharactersInRange:range withString:@"]"];
    
    NSLog(@"jsonString = %@",jsonString);
    return jsonString;
}
+ (NSString *)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
@end
